package com.zw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zw.commons.utlis.MenuHelper;
import com.zw.commons.utlis.RouterHelper;
import com.zw.object.result.Result;
import com.zw.object.system.SysMenu;
import com.zw.object.system.SysRoleMenu;
import com.zw.object.vo.AssginMenuVo;
import com.zw.object.vo.RouterVo;
import com.zw.system.mapper.SysMenuMapper;
import com.zw.system.mapper.SysRoleMenuMapper;
import com.zw.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author zw
 * @since 2022-12-07
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     *                  获取菜单业务，树形结构
     *                      1. 获取全部的菜单列表
     *                      2. 构建树形结构
     * @return Result
     */
    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenuList = baseMapper.selectList(null);
        if (CollectionUtils.isEmpty(sysMenuList)){
            return new ArrayList<>();
        }
        return MenuHelper.buildTree(sysMenuList);
    }

    /**
     *                      新增菜单业务
     *
     * @param permission    参数实体类对象
     * @return              Result
     */
    @Override
    public Result saveMenu(SysMenu permission) {
        int row = baseMapper.insert(permission);
        if(row > 0){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     *                      修改菜单业务
     *
     * @param permission    参数实体类对象
     * @return              Result
     */
    @Override
    public Result updateMenu(SysMenu permission) {
        int row = baseMapper.updateById(permission);
        if(row > 0){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     *                  删除菜单
     *                      1. 判断是否存在子节点
     * @param id        ID
     * @return          Result
     */
    @Override
    public Result deleteMenuById(String id) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId,id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if(count > 0){
            return Result.fail().message("存在子菜单,删除失败!");
        }
        baseMapper.deleteById(id);
        return Result.ok();
    }

    /**
     *                  根据角色ID获取菜单业务
     *                      1. 获取所有状态为激活的菜单
     *                      2. 获取角色已分配的菜单
     *                      3， 构建树形结构返回
     * @param roleId    角色ID参数
     * @return          Result
     */
    @Override
    public Result findMenuByRoleId(String roleId) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getStatus,"1");
        List<SysMenu> sysMenuList = baseMapper.selectList(queryWrapper);

        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,roleId)
                .select(SysRoleMenu::getMenuId);
        List<SysRoleMenu> roleMenuList = sysRoleMenuMapper.selectList(wrapper);
        List<String> menuIdsList = roleMenuList.
                stream()
                        .map(roleMenu -> roleMenu.getMenuId())
                        .collect(Collectors.toList());
        sysMenuList.forEach(sysMenu -> {
            if(menuIdsList.contains(sysMenu.getId())){
//                表示角色已经分配的菜单
                sysMenu.setSelect(true);
            }else {
                sysMenu.setSelect(false);
            }
        });
//        构建树形结构
        List<SysMenu> menus = MenuHelper.buildTree(sysMenuList);
        return Result.ok(menus);
    }

    /**
     *                      保存角色菜单业务
     *                          1. 删除已有菜单权限
     *                          2. 添加新权限
     * @param assignMenuVo  参数实体类对象
     * @return              Result
     */
    @Override
    public Result saveMenuByRoleId(AssginMenuVo assignMenuVo) {
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId,assignMenuVo.getRoleId());
        sysRoleMenuMapper.delete(queryWrapper);
        assignMenuVo.getMenuIdList().stream().forEach(menuId ->{
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(assignMenuVo.getRoleId());
            sysRoleMenuMapper.insert(roleMenu);
        });
        return Result.ok();
    }

    /**
     *                  根据用ID获取菜单权限值
     *                      1. 查询菜单，id为1默认操作所有权限
     *                      2. 根据id查询菜单
     *                      3. 构建树形结构
     *                      4. 构建路由结构
     * @param userId    参数用户ID
     * @return          List<Router>
     */
    @Override
    public List<RouterVo> findUserMenuList(String userId) {
        List<SysMenu> sysMenuList = null;
        if("1".equals(userId)){
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getStatus,"1")
                            .orderByDesc(SysMenu::getSortValue);
            sysMenuList = baseMapper.selectList(queryWrapper);
        }else {
            sysMenuList = sysMenuMapper.findUserMenuList(userId);
        }
//        构建树形结构
        List<SysMenu> sysMenuListTree = MenuHelper.buildTree(sysMenuList);
//        构建路由结构
        List<RouterVo> routerVoList = RouterHelper.buildRouters(sysMenuListTree);
        return routerVoList;
    }

    /**
     * 根据用户ID获取按钮权限值
     *
     * @param userId 参数用户ID
     * @return List<String>
     */
    @Override
    public List<String> findUserPermsList(String userId) {
        List<SysMenu> sysMenuList = new ArrayList<>();
        if("1".equals(userId)){
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getStatus,1);
            sysMenuList = baseMapper.selectList(queryWrapper);
        }else {
            sysMenuList = sysMenuMapper.findUserMenuList(userId);
        }
//        数据处理
        //创建返回的集合

//        sysMenuList.stream()
//                .filter(sysMenu -> sysMenu.getType() == 2)
//                .forEach(sysMenu -> sysMenu.getPerms());

        List<String> stringList = sysMenuList.stream()
                .filter(sysMenu -> sysMenu.getType() == 2)
                .map(SysMenu::getPerms)
                .collect(Collectors.toList());
        log.info("SysMenuServiceImpl.findUserPermsList业务结束，结果:{}",stringList);
        return stringList;
    }
}
